package com.sky.controller.user;

import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.entity.AddressBook;
import com.sky.result.Result;
import com.sky.service.AddressBookService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.ReactiveSubscription;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@Slf4j
@RequestMapping("/user/addressBook")
public class AddressBookController {

    @Autowired
    private AddressBookService addressBookService;

    @PostMapping
    public Result save(@RequestBody AddressBook addressBook) {
        addressBookService.save(addressBook);
        return Result.success();
    }

    @GetMapping("/list")
    public Result<List<AddressBook>> list() {
        AddressBook addressBook = new AddressBook();
        addressBook.setUserId(BaseContext.getCurrentId());
        List<AddressBook> addressBooks=addressBookService.getByCondition(addressBook);
        return Result.success(addressBooks);
    }

    @GetMapping("/{id}")
    public Result<AddressBook> findById(@PathVariable Long id) {
         AddressBook addressBook=addressBookService.getById(id);
         return Result.success(addressBook);
    }

    @GetMapping("/default")
    public Result<AddressBook> findDefault() {
        AddressBook addressBook = new AddressBook();
        addressBook.setUserId(BaseContext.getCurrentId());
        addressBook.setIsDefault(1);
        List<AddressBook> addressBooks=addressBookService.getByCondition(addressBook);
        if(addressBooks==null||addressBooks.size()==0){
            return Result.error(MessageConstant.NO_DEFAULT_ADDRESS);
        }
        return Result.success(addressBooks.get(0));
    }

    //前端发的请求为：http://localhost:8080/user/addressBook/?id=3
    //这比API接口文档多了个"/"
    @DeleteMapping("/")
    public Result deleteById(Long id) {
        log.info("delete: {}",id);
        addressBookService.delete(id);
        return Result.success();
    }

    @PutMapping
    public Result update(@RequestBody AddressBook addressBook) {
        addressBookService.update(addressBook);
        return Result.success();
    }

    //这个接口的参数设计不合理，应该只要传id即可
    @PutMapping("/default")
    public Result setDefault(@RequestBody AddressBook addressBook) {
        addressBookService.setDefault(addressBook);
        return Result.success();
    }


}
